<?php

namespace App\Console\Commands;

use App\Models\IndicatorsDailySummary;
use App\Models\IndicatorsMonthlySummary;
use App\Models\Partner;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;

class AccumulatePartnerCommission extends Command
{
    /**
     * 命令名称及签名
     *
     * @var string
     */
    protected $signature = 'migrate:accumulate_partner_commission';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = '累计单独某一天合伙人佣金(按照当前的代理所属合伙人)';

    public function handle()
    {
        $version = Str::random(8);
        $operationPrefix = 'accumulate_partner_commission_' . $version;
        $this->output->text('此次操作版本号:' . $version);

        // 所有的合伙人
        $partners = Partner::query()->withTrashed()->pluck('agent_id');

        // 哪一天
        $day = '2020-12-31';

        // 遍历 日期统计表
        $this->output->text('开始汇总代理单日佣金');
        IndicatorsDailySummary::query()
            ->join('agents as ag', 'indicators_daily_summary.agent_id', '=', 'ag.id')
            ->where('indicators_daily_summary.type', 1)
            ->where('indicators_daily_summary.day', $day) // 单独某一天
            ->where('indicators_daily_summary.commission_summary', '>', 0)
            ->whereIn('ag.affiliated_partner', $partners) // 会有些(可能是老系统过来的)奇怪数据,这里按照新系统的合伙人 ID 来
            ->select(['indicators_daily_summary.id', 'indicators_daily_summary.agent_id', 'indicators_daily_summary.day', 'indicators_daily_summary.commission_summary', 'ag.affiliated_partner'])
            ->eachById(function ($summary) use ($operationPrefix) {
                // 统计行 的 代理 所属合伙人
                $partner = $summary['affiliated_partner'];
                // redis 合伙人增加按日的佣金
                Redis::hincrby($operationPrefix . ':day_' . $summary['day'], $partner, $summary['commission_summary']);
                // redis 合伙人总佣金
                Redis::hincrby($operationPrefix . '_partners', $partner, $summary['commission_summary']);
            }, 2000, 'indicators_daily_summary.id', 'id');
        $this->output->text('结束汇总代理单日佣金');

        // 更新合伙人按日佣金
        $this->output->text('更新合伙人按日佣金');
        // 哪一月
        $month = Carbon::parse($day)->format('Ym');
        // 当天的合伙人 => 佣金
        foreach (Redis::hgetall($operationPrefix . ':day_' . $day) as $partner => $dayCommission) {
            // 累加到 月 维度的合伙人佣金
            Redis::hincrby($operationPrefix . ':month_' . $month, $partner, $dayCommission);
            // 更新 日 维度数据到数据库中
            IndicatorsDailySummary::query()->updateOrCreate(
                ['agent_id' => $partner, 'day' => $day, 'type' => IndicatorsDailySummary::TYPE_PARTNER],
                ['commission_summary' => $dayCommission]
            );
        }
        $this->output->text('结束更新合伙人按日佣金');

        // 累加合伙人按月佣金
        $this->output->text('更新合伙人按月佣金');
        // 当月的合伙人 => 佣金
        foreach (Redis::hgetall($operationPrefix . ':month_' . $month) as $partner => $monthCommission) {
            // 到 月 维度数据库中
            $monthlySummary = IndicatorsMonthlySummary::query()->firstOrCreate(
                ['agent_id' => $partner, 'month' => $month, 'type' => IndicatorsDailySummary::TYPE_PARTNER],
                ['commission_summary' => $monthCommission]
            );
            // 如果不是本次创建 则增加
            if (!$monthlySummary->wasRecentlyCreated) {
                IndicatorsMonthlySummary::query()->where('id', $monthlySummary->getKey())->increment('commission_summary', $monthCommission);
            }
        }
        $this->output->text('结束更新合伙人按月佣金');

        // 更新合伙人 总佣金
        $this->output->text('更新合伙人 总佣金');
        foreach (Redis::hgetall($operationPrefix . '_partners') as $partner => $totalCommission) {
            Partner::query()->withTrashed()->where('agent_id', $partner)->increment('commission', $totalCommission);
        }
        $this->output->text('结束更新合伙人 总佣金');

        $this->output->success('完成');
    }
}
